import store from '@/store';
import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';
import { UploadImage } from '@/utils/uploadImage';

/**
 * @des: 设置返回按钮
*/
export function setBack(bool) {
  store.dispatch('setBack', bool);
}

export function dateFormat(fmt, date) {
    if (!date) {
      date = new Date();
    }
    let ret = '';
    const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'M+': date.getMinutes().toString(), // 分
        'S+': date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (const k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')));
        };
    };
    return fmt;
}

export function keysort(key, desc) {
  return function(a, b) {
    return a - b;
  };
}

export function getWeek() {
   // 按周日为一周的最后一天计算
    var date = new Date();

    // 今天是这周的第几天
    var today = date.getDay();

    var time = date.getTime();

    var nowDate = new Date(time - (today - 1) * 24 * 3600 * 1000);

    // 开始时间
    var startTime = dateFormat('YY-mm-dd', nowDate); // 日期变换 2018-11-10

    // 今日时间
    var endTime = dateFormat('YY-mm-dd'); // 日期变换  2018-11-10

    return {
      startTime,
      endTime
    };
}

export function getYearNow() {
  const year = new Date().getFullYear();
  const startTime = `${year}-01-01`;
  const endTime = dateFormat('YY-mm-dd');

  return {
    startTime,
    endTime
  };
}

export function getMonthNow() {
  const year = new Date().getFullYear();
  let month = new Date().getMonth() + 1;
  if (String(month).length < 2) {
    month = '0' + month;
  }
  const startTime = `${year}-${month}-01`;
  const endTime = dateFormat('YY-mm-dd');

  return {
    startTime,
    endTime
  };
}

export function secondToDate(result) {
    var h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
    var m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
    var s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
    const results = h + '小时' + m + '分' + s + '秒';
    return results;
}

/*
 * @Description: 获取URL后缀
*/
export function GetQuery(key, url) {
  var after = url || window.location.search;

  // key存在先通过search取值如果取不到就通过hash来取
  after = after.substr(1) || window.location.hash.split('?')[1];

  if (after) {
    var reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)');
    var r = after.match(reg);
    if (r != null) {
      return (r[2]);
    } else {
      return null;
    }
  } else {
    return null;
  }
}
// 获取字符长度 英文1 中文2
export function gblen(str) {
  let len = 0;
  for (let i = 0; i < str.length; i += 1) {
    if (str.charCodeAt(i) > 127 || str.charCodeAt(i) == 94) {
      len += 2;
    } else {
      len += 1;
    }
  }
  return len;
}

// 截取字符串 分中英文
export function setString(str, len) {
  let strlen = 0;
  let s = '';
  for (let i = 0; i < str.length; i += 1) {
    if (str.charCodeAt(i) > 128) {
      strlen += 2;
    } else {
      strlen += 1;
    }
    s += str.charAt(i);
    if (strlen >= len) {
      return `${s}`;
    }
  }
  return s;
}

/**
 * des: 文件类型限制
 * @param {file, isImage}
 * @returns {*}
*/
export function isFile(file, isImage) {
  let reg = /\.(bmp|jpg|jpeg|png|doc|docx|pdf|xls|xlsx)$/;
  // img
  if (isImage == 1) {
    reg = /\.(jpg|jpeg|png)$/;
  }
  // pdf
  if (isImage == 2) {
    reg = /\.(pdf)$/;
  }
  return reg.test(file);
}

/**
 * des: 文件类型限制
 * @param {file, isImage}
 * @returns {*}
*/
export function isPDF(file) {
  const reg = /\.(pdf)$/;
  return reg.test(file);
}

// 驼峰转换下划线
export function toLine(name) {
  return name.replace(/([A-Z])/g, '_$1').toLowerCase();
}

// 循环菜单
export function setmenus(menus) {
  for (const i of menus) {
    if (i.path.includes('?')) {
      const m = i.path.split('?');
      i.path = m[0];
      i.name = i.name.split('?')[0];
      i.meta.params = `?${m[1]}`;
    }
    if (i.children && i.children.length > 0) {
      setmenus(i.children);
    }
  }
}

export function closeWindows() {
  var browserName = navigator.appName;
  // var browserVer = parseInt(navigator.appVersion);
  // alert(browserName + " : "+browserVer);

  // document.getElementById("flashContent").innerHTML = "<br>&nbsp;<font face='Arial' color='blue' size='2'><b> You have been logged out of the Game. Please Close Your Browser Window.</b></font>";

  if (browserName == 'Microsoft Internet Explorer') {
      var ie7 = !!((document.all && !window.opera && window.XMLHttpRequest));
      if (ie7) {
        // This method is required to close a window without any prompt for IE7 & greater versions.
        window.open('', '_parent', '');
        window.close();
      } else {
        // This method is required to close a window without any prompt for IE6
        this.focus();
        self.opener = this;
        self.close();
      }
 } else {
     // For NON-IE Browsers except Firefox which doesnt support Auto Close
     try {
         this.focus();
         self.opener = this;
         self.close();
     } catch (e) {

     }

     try {
         window.open('', '_self', '');
         window.close();
     } catch (e) {

     }
 }
}

export function setRoleFilterAll(list, listAll) {
  const layoutType = list.find(e => {
    return e.layoutType == 'isRole';
  });
  if (layoutType) {
    const roleList = layoutType.options.options;
    console.log('roleList', roleList);
    listAll.forEach(el => {
      if (el.layoutType == 'isRole') return;
      if (el.hasRoleList) return;
      if (el.roleType == 'radio') {
        el.role = roleList.map(e => e.value)[0];
      } else {
        el.role = roleList.map(e => e.value);
      }
      el.hasRoleList = true;
      el.showType = 1;
      if (el.type == 'grid') {
        el.columns.forEach(e => {
          e.list.forEach(el => {
            if (el.roleType == 'radio') {
              el.role = roleList.map(e => e.value)[0];
            } else {
              el.role = roleList.map(e => e.value);
            }
            el.hasRoleList = true;
            el.showType = 1;
          });
        });
      }
      if (el.type == 'group') {
        el.list.forEach(el => {
          if (el.roleType == 'radio') {
            el.role = roleList.map(e => e.value)[0];
          } else {
            el.role = roleList.map(e => e.value);
          }
          el.hasRoleList = true;
          el.showType = 1;
        });
      }
    });
  }

  console.log(layoutType, listAll);
}

export function dataURLtoFile(dataurl, filename) {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    // 转换成file对象
    return new File([u8arr], filename, { type: mime });
    // 转换成成blob对象
    // return new Blob([u8arr],{type:mime});
}

/**
 * des: 下载pdf
 * @param {dom, title, type}
 * type： download 直接下载，upload-auto 自动上传pdf，file 获取文件file
 * @returns {*}
*/
export function downLoadPDF(dom, title, type) {
  return new Promise((resolve, reject) => {
    try {
      const cntElem = document.getElementById(dom);
      const shareContent = cntElem;// 需要截图的包裹的（原生的）DOM 对象
      const width = shareContent.offsetWidth; // 获取dom 宽度
      const height = shareContent.offsetHeight < 1400 ? 1400 : shareContent.offsetHeight; // 获取dom 高度
      const canvas = document.createElement('canvas'); // 创建一个canvas节点
      const scale = 2; // 定义任意放大倍数 支持小数
      canvas.width = width * scale; // 定义canvas 宽度 * 缩放
      canvas.height = height * scale; // 定义canvas高度 *缩放
      canvas.getContext('2d').scale(scale, scale); // 获取context,设置scale
      const opts = {
          scale: 1, // 添加的scale 参数
          canvas: canvas, // 自定义 canvas
          // logging: true, // 日志开关，便于查看html2canvas的内部执行流程
          width: width, // dom 原始宽度
          height: height,
          useCORS: true // 【重要】开启跨域配置
      };
      html2Canvas(shareContent, opts).then(function(canvas) {
        const contentWidth = canvas.width / 2;
        const contentHeight = canvas.height / 2;
        const pageHeight = contentWidth / 592.28 * 841.89;
        let leftHeight = contentHeight;
        let position = 0;
        const imgWidth = 595.28;
        const imgHeight = 592.28 / contentWidth * contentHeight;
        const pageData = canvas.toDataURL('image/jpeg', 1.0);
        // base64AddWaterMaker(pageData).then(pageData => {
          // const x = document.createElement('img');
          // x.src = pageData;
          // document.body.appendChild(x);
          const PDF = new JsPDF('', 'pt', 'a4');
          if (leftHeight < pageHeight) {
            PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
          } else {
            while (leftHeight > 0) {
              PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
              leftHeight -= pageHeight;
              position -= 841.89;
              if (leftHeight > 0) {
                PDF.addPage();
              }
            }
          }

          // 自动下载
          if (type == 'download') {
            PDF.save(title + '.pdf');
            resolve();
          } else if (type == 'upload-auto') {
            // 自动上传并返回文件列表
            const buffer = PDF.output('datauristring');
            const myfile = dataURLtoFile(buffer, title + '.pdf');
            console.log(myfile);
            UploadImage(myfile).then(res => {
              console.log(res);
              resolve(res);
            }).catch((err) => {
              reject((err instanceof Object) ? err.message || err.errorMsg || err.msg : '网络请求错误');
            });
          } else if (type == 'file') {
            // 只返回文件
            const buffer = PDF.output('datauristring');
            const myfile = dataURLtoFile(buffer, title + '.pdf');
            resolve(myfile);
          }
        // });
      });
    } catch (err) {
      console.log(err);
      reject(new Error('出错了'));
    }
  });
}

export const base64AddWaterMaker = (base64Img, wmConfig) => {
    wmConfig = {
      font: 'microsoft yahei', // 字体
      textArray: ['“甬网智享”网络空间综合治理智控平台'], // 水印文本内容，允许数组最大长度3 即：3行水印
      density: 3 // 密度 建议取值范围1-5   值越大，水印越多，可能会导致水印重叠等问题，慎重！！！
    };
    if (wmConfig.textArray.length === 0) {
        console.error('****没有水印内容*****');
        return base64Img;
    }

    return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = new Image();
        let resultBase64 = null;

        img.onload = function() {
            canvas.width = img.width;
            canvas.height = img.height;

            // canvas绘制图片，0 0  为左上角坐标原点
            ctx.drawImage(img, 0, 0);
            // 写入水印
            drawWaterMark(ctx, img.width, img.height, wmConfig);
            resultBase64 = canvas.toDataURL('image/png');

            if (!resultBase64) {
                reject();
            } else {
                resolve(resultBase64);
            }
        };
        img.src = base64Img;
    });
};

// 画布添加水印
const drawWaterMark = (ctx, imgWidth, imgHeight, wmConfig) => {
    let fontSize;
    if (imgWidth >= 3456) {
        fontSize = 50;
    } else if (imgWidth >= 2700) {
        fontSize = 30;
    } else if (imgWidth >= 2000) {
        fontSize = 26;
    } else if (imgWidth >= 1436) {
        fontSize = 20;
    } else if (imgWidth >= 800) {
        fontSize = 12;
    } else if (imgWidth >= 500) {
        fontSize = 10;
    } else {
        fontSize = 8;
    }
    console.log(imgWidth, imgHeight, fontSize);
    ctx.fillStyle = 'rgb(191, 191, 191)';

    ctx.font = `${fontSize}px ${wmConfig.font}`;
    ctx.lineWidth = 1;
    // ctx.fillStyle = 'rgba(255,255,255,0.3)';
    ctx.textAlign = 'left';
    ctx.textBaseline = 'middle';

    // 文字坐标

    const maxPx = Math.max(imgWidth, imgHeight);

    const stepPx = Math.floor(maxPx / wmConfig.density);

    const arrayX = [0];// 初始水印位置 canvas坐标 0 0 点
    while (arrayX[arrayX.length - 1] < maxPx / 2) {
        arrayX.push(arrayX[arrayX.length - 1] + stepPx);
    }
    arrayX.push(...arrayX.slice(1, arrayX.length).map((el) => {
        return -el;
    }));

    console.log(arrayX);

    for (let i = 0; i < arrayX.length; i++) {
        for (let j = 0; j < arrayX.length; j++) {
            ctx.save();
            ctx.translate(imgWidth / 2, imgHeight / 2); /// 画布旋转原点 移到 图片中心
            ctx.rotate(-Math.PI / 5);
            if (wmConfig.textArray.length > 3) {
                wmConfig.textArray = wmConfig.textArray.slice(0, 3);
            }
            wmConfig.textArray.forEach((el, index) => {
                const offsetY = fontSize * index + 2;
                ctx.fillText(el, arrayX[i], arrayX[j] + offsetY);
            });
            ctx.restore();
        }
    }
};

export function downloadFileUrl(url, fileName) {
  const elink = document.createElement('a');

  elink.href = url;

  elink.setAttribute('download', fileName);

  elink.style.display = 'none';

  document.body.appendChild(elink);

  setTimeout(() => {
    elink.click();

    document.body.removeChild(elink);
  }, 66);
}

export function getOneArr(arr) {
  const data = JSON.parse(JSON.stringify(arr));
  const newData = [];
  const callback = (item) => {
    (item.childList || (item.childList = [])).map(v => {
      callback(v);
    });
    delete item.childList;
    newData.push(item);
  };
  data.map(v => callback(v));
  return newData;
}

export function requestFullscreen() {
  const docElm = document.documentElement;
  if (docElm.requestFullscreen) {
    docElm.requestFullscreen();
  } else if (docElm.msRequestFullscreen) {
    docElm.msRequestFullscreen();
  } else if (docElm.mozRequestFullScreen) {
    docElm.mozRequestFullScreen();
  } else if (docElm.webkitRequestFullScreen) {
    docElm.webkitRequestFullScreen();
  }
}

export function exitFullScreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitCancelFullScreen) {
    document.webkitCancelFullScreen();
  }
}

export function removeHTMLTags(str) {
 return str.replace(/<[^>]*>/g, '');
}

// 校验http/https url
export function isURL(url) {
  // eslint-disable-next-line no-useless-escape
  const pattern = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
  return pattern.test(url);
}
